package org.jeecg.modules.sggg.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.util.Strings;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.modules.sggg.entity.BltGwJbxxjlb;
import org.jeecg.modules.sggg.entity.BltGwOrg;
import org.jeecg.modules.sggg.entity.SgMember;
import org.jeecg.modules.sggg.service.IBltGwJbxxjlbService;
import org.jeecg.modules.sggg.service.IBltGwOrgService;
import org.jeecg.modules.sggg.service.ISgMemberService;
import org.jeecg.modules.system.entity.SysDepart;
import org.jeecg.modules.system.service.ISysDepartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

/**
 * @Description: 博乐通公卫基本信息记录表
 * @Author: jeecg-boot
 * @Date: 2024-07-01
 * @Version: V1.0
 */
@Api(tags = "blt_gw_jbxxjlb")
@RestController
@RequestMapping("/sggg/bltGwJbxxjlb")
@Slf4j
public class BltGwJbxxjlbController extends JeecgController<BltGwJbxxjlb, IBltGwJbxxjlbService> {
    @Autowired
    private IBltGwJbxxjlbService bltGwJbxxjlbService;

    @Autowired
    private IBltGwOrgService bltGwOrgService;

    @Autowired
    private ISgMemberService sgMemberService;

    @Autowired
    private ISysDepartService sysDepartService;

    /**
     * 分页列表查询
     *
     * @param bltGwJbxxjlb
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    //@AutoLog(value = "blt_gw_jbxxjlb-分页列表查询")
    @ApiOperation(value = "blt_gw_jbxxjlb-分页列表查询", notes = "blt_gw_jbxxjlb-分页列表查询")
    @GetMapping(value = "/list")
    public Result<IPage<BltGwJbxxjlb>> queryPageList(BltGwJbxxjlb bltGwJbxxjlb,
                                                     @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                     @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                     HttpServletRequest req) {
        QueryWrapper<BltGwJbxxjlb> queryWrapper = QueryGenerator.initQueryWrapper(bltGwJbxxjlb, req.getParameterMap());
        Page<BltGwJbxxjlb> page = new Page<>(pageNo, pageSize);
        IPage<BltGwJbxxjlb> pageList = bltGwJbxxjlbService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    /**
     * 添加
     *
     * @param bltGwJbxxjlb
     * @return
     */
    @AutoLog(value = "blt_gw_jbxxjlb-添加")
    @ApiOperation(value = "blt_gw_jbxxjlb-添加", notes = "blt_gw_jbxxjlb-添加")
    //@RequiresPermissions("org.jeecg.modules:blt_gw_jbxxjlb:add")
    @PostMapping(value = "/add")
    public Result<String> add(@RequestBody BltGwJbxxjlb bltGwJbxxjlb) {
        bltGwJbxxjlbService.save(bltGwJbxxjlb);
        return Result.OK("添加成功！");
    }

    /**
     * 编辑
     *
     * @param bltGwJbxxjlb
     * @return
     */
    @AutoLog(value = "blt_gw_jbxxjlb-编辑")
    @ApiOperation(value = "blt_gw_jbxxjlb-编辑", notes = "blt_gw_jbxxjlb-编辑")
    //@RequiresPermissions("org.jeecg.modules:blt_gw_jbxxjlb:edit")
    @RequestMapping(value = "/edit", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<String> edit(@RequestBody BltGwJbxxjlb bltGwJbxxjlb) {
        bltGwJbxxjlbService.updateById(bltGwJbxxjlb);
        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "blt_gw_jbxxjlb-通过id删除")
    @ApiOperation(value = "blt_gw_jbxxjlb-通过id删除", notes = "blt_gw_jbxxjlb-通过id删除")
    //@RequiresPermissions("org.jeecg.modules:blt_gw_jbxxjlb:delete")
    @DeleteMapping(value = "/delete")
    public Result<String> delete(@RequestParam(name = "id", required = true) String id) {
        bltGwJbxxjlbService.removeById(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "blt_gw_jbxxjlb-批量删除")
    @ApiOperation(value = "blt_gw_jbxxjlb-批量删除", notes = "blt_gw_jbxxjlb-批量删除")
    //@RequiresPermissions("org.jeecg.modules:blt_gw_jbxxjlb:deleteBatch")
    @DeleteMapping(value = "/deleteBatch")
    public Result<String> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.bltGwJbxxjlbService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功!");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    //@AutoLog(value = "blt_gw_jbxxjlb-通过id查询")
    @ApiOperation(value = "blt_gw_jbxxjlb-通过id查询", notes = "blt_gw_jbxxjlb-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<BltGwJbxxjlb> queryById(@RequestParam(name = "id", required = true) String id) {
        BltGwJbxxjlb bltGwJbxxjlb = bltGwJbxxjlbService.getById(id);
        if (bltGwJbxxjlb == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(bltGwJbxxjlb);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param bltGwJbxxjlb
     */
    //@RequiresPermissions("org.jeecg.modules:blt_gw_jbxxjlb:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, BltGwJbxxjlb bltGwJbxxjlb) {
        return super.exportXls(request, bltGwJbxxjlb, BltGwJbxxjlb.class, "blt_gw_jbxxjlb");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    //@RequiresPermissions("blt_gw_jbxxjlb:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, BltGwJbxxjlb.class);
    }

    /**
     * 同步博乐通公卫居民数据
     *
     * @return
     */
    @PostMapping(value = "/handleDataSync")
    public Result<String> handleDataSync() {
        // 获取用户信息列表
        List<BltGwJbxxjlb> list = bltGwJbxxjlbService.list();

        // 创建固定大小的线程池，线程数量等于可用处理器数量
        ExecutorService executorService = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());

        // 用于存储每个线程处理结果的Future列表
        List<Future<SgMember>> futures = new ArrayList<>();

        // 并行处理每个客户信息
        for (BltGwJbxxjlb bltGwJbxxjlb : list) {
            futures.add(executorService.submit(() -> processMember_DataSync(bltGwJbxxjlb)));
        }

        // 存储所有成功处理的会员信息
        List<SgMember> sgMembers = new ArrayList<>();
        // 遍历Future列表，提取处理结果
        for (Future<SgMember> future : futures) {
            try {
                SgMember sgMember = future.get();
                if (sgMember != null) {
                    sgMembers.add(sgMember);
                }
            } catch (InterruptedException | ExecutionException e) {
                e.printStackTrace();
            }
        }

        // 批量保存会员信息
        sgMemberService.saveBatch(sgMembers);
        // 关闭线程池
        executorService.shutdown();

        log.info("同步数据完成~~~");
        return Result.ok();
    }

    /**
     * 为居民表中机构编码为空的居民同步机构编码
     *
     * @return
     */
    @PostMapping(value = "/handleMemberOrgSync")
    @Transactional
    public Result<String> handleMemberOrgSync() {
        // 查询需要同步组织信息的会员列表
        List<SgMember> sgMemberList = sgMemberService.list(
                new QueryWrapper<SgMember>()
                        .isNull("sys_org_code")
                        .notIn("id_card", "15222319790306071x")
        );

        // 计算分块的大小和块的数量
        int chunkSize = 1000;
        int numberOfChunks = (int) Math.ceil((double) sgMemberList.size() / chunkSize);
        List<List<SgMember>> chunks = new ArrayList<>();

        // 将居民列表分块
        for (int i = 0; i < numberOfChunks; i++) {
            int start = i * chunkSize;
            int end = Math.min(start + chunkSize, sgMemberList.size());
            chunks.add(sgMemberList.subList(start, end));
        }

        // 创建一个固定大小的线程池，用于并行处理分块任务
        ExecutorService executorService = Executors.newFixedThreadPool(10);
        List<Future<List<SgMember>>> futures = new ArrayList<>();

        // 提交每个分块处理任务到线程池
        for (List<SgMember> chunk : chunks) {
            futures.add(executorService.submit(() -> {
                List<SgMember> processedMembers = new ArrayList<>();
                for (SgMember sgMember : chunk) {
                    BltGwJbxxjlb bltGwJbxxjlb = bltGwJbxxjlbService.getOne(new QueryWrapper<BltGwJbxxjlb>().eq("sfzh", sgMember.getIdCard()));
                    // 如果个人信息不存在或机构id为空，则跳过
                    if (bltGwJbxxjlb == null || Strings.isBlank(bltGwJbxxjlb.getOrgId())) {
                        continue;
                    }
                    SysDepart depart = sysDepartService.getOne(new QueryWrapper<SysDepart>().eq("yq_id", bltGwJbxxjlb.getOrgId()));
                    // 如果找到对应的机构信息，则更新会员的机构编码
                    if (depart != null) {
                        sgMember.setSysOrgCode(depart.getOrgCode());
                        processedMembers.add(sgMember);
                    }
                }
                return processedMembers;
            }));
        }

        // 收集并合并所有分块处理的结果
        List<SgMember> processedMembers = new ArrayList<>();
        for (Future<List<SgMember>> future : futures) {
            try {
                processedMembers.addAll(future.get());
            } catch (InterruptedException | ExecutionException e) {
                log.error("Error processing chunk", e);
            }
        }

        // 关闭线程池
        executorService.shutdown();

        // 更新处理过的会员信息至数据库
        try {
            if (!processedMembers.isEmpty()) {
                sgMemberService.updateBatchById(processedMembers);
                log.info("同步数据完成，共处理{}条记录", processedMembers.size());
            } else {
                log.info("没有需要处理的记录");
            }
        } catch (Exception e) {
            log.error("同步数据时发生错误", e);
            throw e;
        }

        return Result.ok();
    }

    /**
     * 同步博乐通机构id到sys_depart表
     *
     * @return
     */
    @PostMapping(value = "/handleDepartSync")
    public Result<String> handleDepartSync() {
        List<SysDepart> sysDepartList = sysDepartService.list(new QueryWrapper<SysDepart>().like("create_time", "2024-07-04"));

        for (SysDepart sysDepart : sysDepartList) {
            List<BltGwOrg> bltGwOrgList = bltGwOrgService.list(new QueryWrapper<BltGwOrg>().eq("org_name", sysDepart.getDepartName()));
            if (bltGwOrgList.size() != 1) {
                continue;
            }
            sysDepart.setYqId(Long.valueOf(bltGwOrgList.get(0).getId()));
            sysDepartService.updateById(sysDepart);
        }

        return Result.OK();
    }

    private SgMember processMember_DataSync(BltGwJbxxjlb bltGwJbxxjlb) {
        SgMember member = sgMemberService.getOne(new QueryWrapper<SgMember>().eq("id_card", bltGwJbxxjlb.getSfzh()));
        if (member != null) {
            return null;
        }

        SgMember sgMember = new SgMember();
        sgMember.setName(bltGwJbxxjlb.getHzmc());
        sgMember.setIdCard(bltGwJbxxjlb.getSfzh());
        if (Strings.isNotBlank(bltGwJbxxjlb.getSj())) {
            sgMember.setPhone(bltGwJbxxjlb.getSj());
        }
        sgMember.setBirthday(bltGwJbxxjlb.getCsrq());
        sgMember.setSex(bltGwJbxxjlb.getXb().equals("1") ? 0 : 1);
        if (Strings.isNotBlank(bltGwJbxxjlb.getXzz())) {
            sgMember.setAddress(bltGwJbxxjlb.getXzz());
        }
        if (Strings.isNotBlank(bltGwJbxxjlb.getSsshengbh()) && Strings.isNotBlank(bltGwJbxxjlb.getSssbh())
                && Strings.isNotBlank(bltGwJbxxjlb.getSsxbh()) && Strings.isNotBlank(bltGwJbxxjlb.getSsxzbh())) {
            sgMember.setRegion(String.format("%s/%s/%s/%s", bltGwJbxxjlb.getSsshengbh(), bltGwJbxxjlb.getSssbh(), bltGwJbxxjlb.getSsxbh(), bltGwJbxxjlb.getSsxzbh()));
        }
        if (Strings.isNotBlank(bltGwJbxxjlb.getRqlx())) {
            sgMember.setThreeTag(replaceThreeTag(bltGwJbxxjlb.getRqlx()));
        }
        if (Strings.isNotBlank(bltGwJbxxjlb.getOrgId())) {
            List<SysDepart> departList = sysDepartService.list(new QueryWrapper<SysDepart>().eq("yq_id", bltGwJbxxjlb.getOrgId()));
            if (departList.size() == 1) {
                sgMember.setSysOrgCode(departList.get(0).getOrgCode());
            }
        }

        // 设置预警值
        sgMember.setSbpvalMin(90.0);
        sgMember.setSbpvalMax(140.0);

        sgMember.setDbpvalMin(60.0);
        sgMember.setDbpvalMax(90.0);

        sgMember.setBodyfatMin(6.0);
        sgMember.setBodyfatMax(14.0);

        sgMember.setSugarMin(1.1);
        sgMember.setSugarMax(6.1);

        sgMember.setBloodMin(0.0);
        sgMember.setBloodMax(5.18);

        return sgMember;
    }

    private String replaceThreeTag(String rqlx) {
        // 创建三方平台与我方平台标识的映射关系
        Map<String, String> mapping = new HashMap<>();
        mapping.put("6", "0");  // 高血压
        mapping.put("7", "1");  // 高血糖
        mapping.put("8", "5");  // 冠心病

        // 处理替换
        String[] parts = rqlx.split(",");
        StringBuilder result = new StringBuilder();
        for (String part : parts) {
            if (mapping.containsKey(part)) {
                result.append(mapping.get(part)).append(",");
            }
        }

        // 移除最后一个多余的逗号
        if (result.length() > 0) {
            result.setLength(result.length() - 1);
        }

        return result.toString();
    }

}
